package entityAdapter

import (
	"fmt"
	"gitee.com/fierce_wolf/go-fox-edge-common/commConfig"
	"gitee.com/fierce_wolf/go-fox-edge-common/commEntityManager"
	"gitee.com/fierce_wolf/go-fox-edge-common/commSql"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Map"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Number"
	"time"
)

type DeviceOperateAdapter struct {
	lastTime int64
}

func (e *DeviceOperateAdapter) ClearOperateRecord() {
	// 定义一个最终的异常拦截，用来防止可能的代码BUG
	defer func() {
		if r := recover(); r != nil {
		}
	}()

	if !commEntityManager.EntityManager.Initialized {
		return
	}

	// 检查：是否需要记录
	configs, err := commConfig.GetConfigParam("serverConfig")
	if err != nil {
		return
	}
	deviceHistory := Map.GetMap(configs, "operateRecord", make(map[string]interface{}))
	if !Map.GetBool(deviceHistory, "enable", false) {
		return
	}

	value := Map.GetOrDefault(configs, "operateRecord", make(map[string]interface{}))
	params := value.(map[string]interface{})

	maxCount := Number.MakeInt64(Map.GetOrDefault(params, "maxCount", 1000000))
	period := Number.MakeInt64(Map.GetOrDefault(params, "period", 3600))

	// 检查：执行周期是否到达
	currentTime := time.Now().UnixMilli()
	if (currentTime - e.lastTime) < period*1000 {
		return
	}
	e.lastTime = currentTime

	// 除了最近的maxCount条数据，旧数据全部删除
	e.deleteOperateRecord(maxCount)
}

func (e *DeviceOperateAdapter) deleteOperateRecord(retainCount int64) {
	// 执行SQL删除语句
	sql := fmt.Sprintf("DELETE FROM tb_operate_record WHERE id NOT IN (SELECT t1.id AS id FROM (SELECT t.id FROM tb_operate_record t ORDER BY t.id LIMIT %v) t1)", retainCount)
	commSql.Client.Exec(sql, nil)
}
